//
//  FeedBackViewController.m
//  PrintPort
//
//  Created by 欧阳政 on 2017/11/15.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "FeedBackViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "TZImagePickerController.h"
#import <Photos/Photos.h>

@interface FeedBackViewController ()<TZImagePickerControllerDelegate,UITextViewDelegate,UITextFieldDelegate>
{
    TZImagePickerController *imagePickerVc;
    UITextField *phoneField;
}
@property (nonatomic, strong)UIView *backView;
@property (nonatomic, strong)UITextView *contentView;
@property (nonatomic, strong)UILabel *strLengthLab;
@property (nonatomic, strong)NSMutableArray *imageAry;
@property (nonatomic, strong)NSString *pladerStr;


@end

@implementation FeedBackViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    _pladerStr = @"请输入遇到的问题或建议...";
    _imageAry = [NSMutableArray arrayWithCapacity:0];
    [self creatUI];
}


- (void)creatUI
{
    self.navigationController.navigationBar.translucent = NO;
    if (_titleStr) {
        self.navigationItem.title = _titleStr;
        self.navigationController.navigationBar.hidden = NO;
    } else {
        self.navigationItem.title = @"意见反馈";
    }
    self.view.backgroundColor = BacksColor;
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 170*displaywidth)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    self.contentView = [[UITextView alloc] initWithFrame:CGRectMake(15*displaywidth, 0, SCREEN_WIDTH-30*displaywidth, 70*displaywidth)];
    _contentView.delegate = self;
    _contentView.text = _pladerStr;
    _contentView.textColor = RGB(179, 179, 179);
    [whiteView addSubview:_contentView];
    self.strLengthLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 70*displaywidth, SCREEN_WIDTH-30*displaywidth, 15*displaywidth) Font:10.0 Text:@"0/300" Color:RGB(179, 179, 179)];
    _strLengthLab.textAlignment = NSTextAlignmentRight;
    [whiteView addSubview:_strLengthLab];
    

    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 90*displaywidth, SCREEN_WIDTH, 80*displaywidth)];
    _backView.backgroundColor = [UIColor whiteColor];
    [whiteView addSubview:_backView];
    [self creatImgView];
    
    UIView *secondView = [[UIView alloc] initWithFrame:CGRectMake(0, 190*displaywidth, SCREEN_WIDTH, 45*displaywidth)];
    secondView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:secondView];
    UILabel *titLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, 100*displaywidth, 35*displaywidth) Font:13.0 Text:@"联系电话" Color:RGB(77, 77, 77)];
    [secondView addSubview:titLab];
    UITextField *textfield = [ZCControl createTextFieldWithFrame:CGRectMake(115*displaywidth, 5*displaywidth, SCREEN_WIDTH-130*displaywidth, 35*displaywidth) placeholder:@"输入电话号码" passWord:NO leftImageView:nil rightImageView:nil Font:13.0];
    [textfield setValue:RGB(179, 179, 179) forKeyPath:@"_placeholderLabel.textColor"];
    textfield.textColor = RGB(77, 77, 77);
    textfield.delegate = self;
    textfield.textAlignment = NSTextAlignmentLeft;
    textfield.keyboardType = UIKeyboardTypeNumberPad;
    [secondView addSubview:textfield];
    phoneField = textfield;
    
    UIButton *loginBtn = [ZCControl createButtonWithFrame:CGRectMake(60*displaywidth , 290*displaywidth, SCREEN_WIDTH-120*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(pushBtnAction) Title:@"提交" Font:15.0];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.backgroundColor = ThemeColor;
    [loginBtn.layer setMasksToBounds:YES];
    [loginBtn.layer setCornerRadius:5*displaywidth];
    [self.view addSubview:loginBtn];
}



- (void)creatImgView
{
    
    [_backView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CGFloat width = (SCREEN_WIDTH-280*displaywidth)/4;
    for (int i = 0; i < _imageAry.count + 1; i++)
    {
        
        if (i == _imageAry.count)
        {
            UIButton *imageBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth+i*(width+50*displaywidth),5*displaywidth, 50*displaywidth, 50*displaywidth) ImageName:nil Target:self Action:@selector(imageBtn:) Title:nil Font:12.0];
            [imageBtn setImage:[UIImage imageNamed:@"tianjiatupiankua"] forState:UIControlStateNormal];
            imageBtn.tag = 100+i;
            [_backView addSubview:imageBtn];
        }
        else
        {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(15*displaywidth+i*(width+50*displaywidth),5*displaywidth, 50*displaywidth, 50*displaywidth)];
            imageView.image = _imageAry[i];
            [_backView addSubview:imageView];
            UIButton *delectBtn = [ZCControl createButtonWithFrame:CGRectMake(imageView.frame.origin.x+50*displaywidth-10*displaywidth, imageView.frame.origin.y-10*displaywidth, 20*displaywidth, 20*displaywidth) ImageName:@"delected" Target:self Action:@selector(imageBtn:) Title:nil Font:12.0];
            delectBtn.tag = 100+i;
            [_backView addSubview:delectBtn];
        }
        
        
    }
    if (_imageAry.count == 0)
    {
        UILabel *stateLabel = [ZCControl createLabelWithFrame:CGRectMake(75*displaywidth, 10*displayheight, SCREEN_WIDTH-90*displaywidth, 22*displayheight) Font:11.0 Text:@"添加图片说明" Color:RGB(77, 77, 77)];
        [_backView addSubview:stateLabel];
        
        UILabel *TostLabel = [ZCControl createLabelWithFrame:CGRectMake(75*displaywidth, 32*displayheight, SCREEN_WIDTH-90*displaywidth, 22*displayheight) Font:11.0 Text:@"(最多5张，支持JPG、PNG、BMP图片格式)" Color:RGB(179, 179, 179)];
        TostLabel.numberOfLines = 0;
        [_backView addSubview:TostLabel];
    }
}

- (void)imageBtn:(UIButton *)btn
{
    [self.view endEditing:YES];
    NSInteger tag = btn.tag-100;
    if (tag == _imageAry.count)
    {
        NSInteger num = 5-_imageAry.count;
        imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:num delegate:self];
        imagePickerVc.allowPickingOriginalPhoto = NO;
        imagePickerVc.allowPickingVideo = NO;
        __weak __typeof(self)weakSelf = self;
        [imagePickerVc setDidFinishPickingPhotosWithInfosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto,NSArray<NSDictionary *> *infos){
            NSArray *imgAry = photos;
            [weakSelf.imageAry addObjectsFromArray:imgAry];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf creatImgView];
                
            });
           
            
        }];
        
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        
    }
    else
    {
        if (_imageAry.count > tag)
        {
            [_imageAry removeObjectAtIndex:tag];
            [self creatImgView];
        }
        
    }
}

- (void)pushBtnAction
{
    if ([self.contentView.text isEqualToString:_pladerStr])
    {
        [LTools showMBProgressWithText:@"请输入遇到的问题或建议" addToView:self.view];
        return;
    }
    if (phoneField.text.length != 11)
    {
        [LTools showMBProgressWithText:@"请输入11位联系电话" addToView:self.view];
        return;
    }
    if (_imageAry.count > 0)
    {
        WEAKSELF;
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        [HttpTool uploadImageWithPath:SERVER_fileUpload params:nil thumbName:@"file" ImageAry:_imageAry success:^(id json)
         {
             [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
             if ([json server_Getcodecheck])
             {
                 NSArray *imgArray = json[@"data"];
                 if (imgArray.count == 0)
                 {
                     [LTools showMBProgressWithText:@"图片上传出现问题，请重新上传" addToView:weakSelf.view];
                     return;
                 }
                 NSMutableArray *newImgAry = [NSMutableArray arrayWithCapacity:0];
                 for (NSString *imgUrl in imgArray)
                 {
                     NSDictionary *imgDic = @{@"url":imgUrl};
                     [newImgAry addObject:imgDic];
                 }
                 NSDictionary *dic = @{@"content":weakSelf.contentView.text,
                                       @"feedbackImgs":newImgAry,
                                       @"phone":phoneField.text
                                       };
                 [weakSelf requestmsgFeedback:dic];
             }
             else
             {
                 [LTools showMBProgressWithText:json[@"msg"] addToView:weakSelf.view];
             }
         } failure:^(NSError *error) {
             [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];

         } progress:^(CGFloat progress) {
             
         }];
    }
    else
    {
        NSDictionary *dic = @{@"content":_contentView.text,
                              @"phone":phoneField.text
                              };
        [self requestmsgFeedback:dic];
    }
}

- (void)requestmsgFeedback:(NSDictionary *)dic
{
    WEAKSELF;
    [HYBaseHandler requestmsgFeedbackParmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            [LTools showMBProgressWithText:@"反馈成功" addToView:sharedDelegate.window];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

//开始编辑
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    textView.textColor = RGB(77, 77, 77);
    if ([textView.text isEqualToString:_pladerStr])
    {
        textView.text= @"";
    }
}



//结束编辑
- (void)textViewDidEndEditing:(UITextView *)textView
{
    _strLengthLab.text = [NSString stringWithFormat:@"%ld/300",textView.text.length];
    if ([textView.text isEqualToString:@""])
    {
        textView.text= _pladerStr;
        textView.textColor = RGB(179, 179, 179);
    }
    
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    _strLengthLab.text = [NSString stringWithFormat:@"%ld/300",textView.text.length];
    NSInteger  charactersAfterChange = textView.text.length + text.length - range.length;
    if (charactersAfterChange >= 300)
    {
        return NO;
    }
    //删除
    if ([text isEqualToString:@""]) {
        return YES;
    }
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
